import { MessageBox } from "@/modules/components/dialog";
import $ from "jquery";
import { Loading } from "@/modules/components/loading";
import "../styles/main.scss";
import "./resource";
import { String } from "@/utils/string";
import { UserManager } from "@/users";
import { LocalUser } from "@/users/local-user";
import { UserFriendlyException } from "@/exceptions/IUserFriendlyException";

$(() => {
  $("#loginButton").on("click", onLogin);

  const url = new URL(window.location.href);
  const parameters = new URLSearchParams(url.search);
  const redirectUrl = parameters.get("redirect");

  async function onLogin() {
    const userName = $("#userNameInput")?.val();
    const password = $("#passwordInput")?.val();

    if (String.isNullOrWhitespace(userName as string)) {
      MessageBox.ShowNitification("输入提示", "请输入用户名！");
      return;
    }

    if (String.isNullOrWhitespace(password as string)) {
      MessageBox.ShowNitification("输入提示", "请输入用户密码！");
      return;
    }

    Loading.Open("正在登录中...");
    try {
      const result = await UserManager.loginAsync(
        userName as string,
        password as string
      );
      if (result != null) {
        LocalUser.setUserInfo(result);

        if (String.isNullOrWhitespace(redirectUrl)) {
          window.location.href = "/mixing-process/home/index.html";
        } else {
          window.location.href = redirectUrl!;
        }
      }
    } catch (err) {
      if (err instanceof UserFriendlyException) {
        MessageBox.ShowNitification("提示", err.message);
      } else {
        console.error(err);
        MessageBox.ShowNitification("提示", "登录错误！");
      }
    } finally {
      Loading.Close();
    }
  }
});
